package cn.framelife.rainbow.db.creator.part;

import java.io.File;
import java.util.List;
import java.util.Set;

import cn.framelife.rainbow.db.entity.SpringProperty;
import cn.framelife.rainbow.util.DatabaseCache;
import cn.framelife.rainbow.util.FileUtil;
import cn.framelife.rainbow.util.FreemarkerUtil;
import cn.framelife.rainbow.util.StringUtil;
import cn.framelife.rainbow.util.xml.SpringXMLUtil;
import cn.framelife.rainbow.util.xml.WebXMLUtil;

public class ConfigFileCreator {
	private String projectName;
	private String packageURL;
	
	public ConfigFileCreator(String projectName, String packageURL) {
		this.projectName = projectName;
		this.packageURL = packageURL;
	}
	
	public void createCodeForSpring(String dialect,List<String> annotatedClasses) throws Exception{
		String springPath = FileUtil.getSpringConfigPath(projectName);
		if(new File(springPath).exists()){
			SpringXMLUtil.updateAnnotatedClasses(springPath, annotatedClasses);
		}else{
			FreemarkerUtil.createSpringConfig(createSpringProperty(springPath, dialect, annotatedClasses));
		}
		
	}
	
	public void createCodeForWeb(Set<String> actionPackages) throws Exception{
		String path = FileUtil.getWebConfigPath(projectName);
		if(WebXMLUtil.isActionNode(path)){
			WebXMLUtil.updateActionPackages(path, actionPackages);
		}else {
			FreemarkerUtil.createWebConfig(path, StringUtil.mergeSetWithSeparator(actionPackages, ","));
		}
	}
	
	/**
	 * 生成Spring配置文件对象
	 *
	 * @param reverseProperty
	 * @param annotatedClasses
	 * @return
	 */
	private SpringProperty createSpringProperty(String path, String dialect,List<String> annotatedClasses) {
		SpringProperty springProperty = new SpringProperty();
		springProperty.setPath(path);
		springProperty.setScanPackage(packageURL);
		springProperty.setAnnotatedClasses(annotatedClasses);
		springProperty.setConnectionProperty(DatabaseCache.getConnectionProperty());
		springProperty.setDialect(dialect);
		springProperty.setServicePackage(packageURL);
		return springProperty;
	}
	
}
